package com.imooc.miaosha.rabbitmq;

import com.imooc.miaosha.domain.MiaoShaUser;
import com.imooc.miaosha.domain.MiaoshaOrder;
import com.imooc.miaosha.redis.RedisService;
import com.imooc.miaosha.service.GoodsService;
import com.imooc.miaosha.service.MiaoshaService;
import com.imooc.miaosha.service.OrderService;
import com.imooc.miaosha.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class MQReceiver {
    @Autowired
    MiaoshaService miaoshaService;
    @Autowired
    GoodsService goodsService;
    @Autowired
    OrderService orderService;

    @RabbitListener(queues = MQConfig.MIAOSHA_QUEUE)
    public void receiveMiaoshaMsg(String miaoshaMessage){
        log.info("miaosha receive msg:" + miaoshaMessage);
        MiaoshaMessage msg = RedisService.stringToBean(miaoshaMessage, MiaoshaMessage.class);

        long goodsId = msg.getGoodsId();
        MiaoShaUser miaoShaUser = msg.getMiaoShaUser();
        GoodsVo goodsVo = goodsService.getGoodsVoByGoodsId(goodsId);

        //判断库存
        int stock = goodsVo.getStockCount();
        if(stock < 0)
            return;

        //判断是否秒杀过了，其实这一步可以省略，在数据库层面已经做过优化了
        MiaoshaOrder miaoshaOrder = orderService.selectMiaoshaOrderByUserIdGoodsId(miaoShaUser.getId(), goodsId);
        if(miaoshaOrder != null)
            return;

        //有库存而且没秒杀过，开始秒杀
        miaoshaService.miaosha(miaoShaUser,goodsVo);
    }

/*    @RabbitListener(queues = MQConfig.QUEUE_NAME1)
    public void receive(byte[] message){
        log.info("1 receive message:" + new String(message));
    }


    @RabbitListener(queues = MQConfig.QUEUE_NAME2)
    public void receive2(byte[] message){
        log.info("2 receive message:" + new String(message));
    }

    @RabbitListener(queues = MQConfig.QUEUE_NAME3)
    public void receive3(byte[] message){
        log.info("3 receive message:" + new String(message));
    }*/

/*    @RabbitListener(queues = MQConfig.QUEUE_NAME1)
    public void receive(String message){
        log.info("1 receive message:" + message);
    }


    @RabbitListener(queues = MQConfig.QUEUE_NAME2)
    public void receive2(String message){
        log.info("2 receive message:" + message);
    }

    @RabbitListener(queues = MQConfig.QUEUE_NAME3)
    public void receive3(String message){
        log.info("3 receive message:" + message);
    }*/
}
